import 'package:flutter/material.dart';
import 'package:x3_charts_core/model/right_stacked_histogram_chart_model.dart';

///**
///* @author hrongyong
///* @date   3/5/21
///* @email hrongyong@gmail.com
///* Description: 右堆积直方图
///*/

class RightStackedHistogramChartPainter extends CustomPainter {
  ///图表数组
  final List<RightStackedHistogramChartModel> chartList;

  ///背景颜色
  final Color backgroundColor;

  ///动画数值
  final Animation<double> repaint;

  ///Y轴示例 - 用于测量Y轴系数宽度
  final String yAxisExample;

  ///X轴最大值
  final int xAxisMax;

  ///绘制X轴线
  final bool drawXAxis;

  ///绘制X轴线刻度
  final bool drawXAxisScale;

  ///绘制Y轴线
  final bool drawYAxis;

  ///绘制Y轴线刻度
  final bool drawYAxisScale;

  ///显示几个横条
  final int showSeveralBars;

  ///默认颜色
  final Color defaultColor;

  RightStackedHistogramChartPainter({
    @required this.chartList,
    @required this.repaint,
    @required this.xAxisMax,
    @required this.yAxisExample,
    this.backgroundColor = Colors.white,
    this.drawXAxis = false,
    this.drawXAxisScale = true,
    this.drawYAxis = true,
    this.drawYAxisScale = true,
    this.showSeveralBars,
    this.defaultColor = Colors.red,
  }) : super(repaint: repaint);

  ///左边间距
  double leftMargin = 0.0;

  ///底部间距
  double bottomMargin = 0.0;

  ///间距
  EdgeInsets chartPadding;

  ///最大宽度高度
  double maxWidth = 0.0;
  double maxHeight = 0.0;

  double yStep = 0.0; // y 间隔

  ///文字
  final TextPainter _textPainter = TextPainter(textDirection: TextDirection.ltr);

  Paint fillPaint = Paint()..color = Colors.red;

  @override
  void paint(Canvas canvas, Size size) {
    if (chartList == null || chartList.length == 0) return;

    ///确定左边和下边的距离
    if (yAxisExample != null) {
      //Y轴系数
      TextPainter painter01 = TextPainter(
          maxLines: 1,
          textDirection: TextDirection.ltr,
          text: TextSpan(
              text: yAxisExample,
              style: TextStyle(
                fontSize: 10,
                fontWeight: FontWeight.bold,
              )));
      painter01.layout();

      leftMargin = painter01.width;
      bottomMargin = painter01.height;
    }
    chartPadding = EdgeInsets.only(left: leftMargin + 2, bottom: bottomMargin + 4, right: 10, top: 10);
    maxWidth = size.width - chartPadding.left - chartPadding.right;
    maxHeight = size.height - chartPadding.top - chartPadding.bottom;
    yStep = showSeveralBars == null ? maxHeight / chartList.length : maxHeight / showSeveralBars;

    ///绘制背景
    canvas.drawRect(Offset.zero & size, Paint()..color = backgroundColor);

    ///移动绘制中心
    canvas.translate(chartPadding.left, maxHeight);

    ///绘制X轴及文本
    _drawXAxisScaleAndText(canvas, size);

    ///绘制Y轴刻度和文本
    _drawYAxisScaleAndText(canvas, size);

    ///绘制横向直方图
    _drawHistogram(canvas, size);

    ///绘制横向直方图的描述
    _drawDescription(canvas, size);
  }

  _drawDescription(Canvas canvas, Size size) {
    canvas.save();
    canvas.translate(0, -maxHeight);
    for (int i = 0; i < chartList.length; i++) {
      ///积累进度
      double accumulation = 0.0;
      chartList[i].stackedCubesList.forEach((element) {
        double dataWidth = element.ratio * maxWidth * repaint.value;
        accumulation += dataWidth;
        _drawDescriptionText(canvas, element.description, Offset(accumulation - (element.ratio * maxWidth / 2), yStep / 2));
      });
      canvas.translate(0, yStep);
    }
    canvas.restore();
  }

  void _drawDescriptionText(Canvas canvas, String str, Offset offset) {
    TextSpan text = TextSpan(text: str, style: TextStyle(fontSize: 8, color: Colors.black, fontWeight: FontWeight.bold));
    _textPainter.text = text;
    _textPainter.layout(); // 进行布局

    Size size = _textPainter.size;

    Offset offsetPos;

    offsetPos = Offset(offset.dx - size.width / 2, offset.dy - size.height / 2);

    _textPainter.paint(canvas, offsetPos);
  }

  _drawHistogram(Canvas canvas, Size size) {
    canvas.save();
    canvas.translate(0, -maxHeight);
    for (int i = 0; i < chartList.length; i++) {
      ///积累进度
      double accumulation = 0.0;
      chartList[i].stackedCubesList.forEach((element) {
        fillPaint..color = element.colors == null ? defaultColor : element.colors;
        double dataWidth = element.ratio * maxWidth * repaint.value;
        canvas.drawRect(Rect.fromLTWH(accumulation, 0, dataWidth, yStep * 0.75).translate(0, yStep * 0.25 * 0.5), fillPaint);
        accumulation += dataWidth;
      });
      canvas.translate(0, yStep);
    }
    canvas.restore();
  }

  _drawYAxisScaleAndText(Canvas canvas, Size size) {
    canvas.save();
    canvas.translate(0, -maxHeight);

    ///Y轴线
    if (drawYAxis) canvas.drawLine(Offset.zero, Offset(0, maxHeight), Paint()..color = Colors.black12);
    canvas.translate(0, yStep / 2);
    for (int i = 0; i < chartList.length; i++) {
      if (drawYAxisScale) canvas.drawLine(Offset.zero, Offset(-4, 0), Paint()..color = Colors.black12);
      if (drawYAxisScale) _drawYAxisText(canvas, title: chartList[i].name, offset: Offset.zero);
      canvas.translate(0, yStep);
    }
    canvas.restore();
  }

  ///绘制Y轴文字
  void _drawYAxisText(
    Canvas canvas, {
    String title,
    Offset offset = Offset.zero,
    double fontSize = 8,
    Color color = Colors.black,
  }) {
    ///绘制标题
    TextSpan text = TextSpan(text: title, style: TextStyle(fontSize: fontSize, color: color));
    _textPainter.text = text;
    _textPainter.layout(); // 进行布局
    Size textSize = _textPainter.size;
    Offset textOffsetPos = Offset(offset.dx - textSize.width - 4, offset.dy - textSize.height / 2);
    _textPainter.paint(canvas, textOffsetPos);
  }

  _drawXAxisScaleAndText(Canvas canvas, Size size) {
    canvas.save();
    double xStep = maxWidth / 10;

    ///x轴线
    if (drawXAxis) canvas.drawLine(Offset.zero, Offset(maxWidth, 0), Paint()..color = Colors.black12);

    ///x轴刻度线
    for (int i = 0; i <= 10; i++) {
      if (drawXAxisScale) canvas.drawLine(Offset(xStep * i, 0), Offset(xStep * i, 4), Paint()..color = Colors.black12);
      if (drawXAxisScale) canvas.drawLine(Offset(-xStep * i, 0), Offset(-xStep * i, 4), Paint()..color = Colors.black12);

      ///x轴线描述
      _drawXAxisText(canvas, title: (xAxisMax / 5 * i).toInt().toString(), offset: Offset(xStep * i, 0));
    }

    canvas.restore();
  }

  ///绘制X轴文字
  void _drawXAxisText(
    Canvas canvas, {
    String title,
    Offset offset = Offset.zero,
    double fontSize = 8,
    Color color = Colors.black,
  }) {
    ///绘制标题
    TextSpan text = TextSpan(text: title, style: TextStyle(fontSize: fontSize, color: color));
    _textPainter.text = text;
    _textPainter.layout(); // 进行布局
    Size textSize = _textPainter.size;
    Offset textOffsetPos = Offset(offset.dx - textSize.width / 2, offset.dy + textSize.height / 3);
    _textPainter.paint(canvas, textOffsetPos);
  }

  @override
  bool shouldRepaint(covariant CustomPainter oldDelegate) => false;
}
